package com.steel.yfmall.cloud.assistant.impl;

import com.alibaba.fastjson.JSON;
import com.steel.yfmall.cloud.assistant.bean.param.zg.APIZgChangerOrderBean;
import com.steel.yfmall.cloud.assistant.bean.param.zg.APIZgChangerOrderDetailsBean;
import com.steel.yfmall.cloud.assistant.bean.param.zg.APIZgChangerOrderMainBean;
import com.steel.yfmall.cloud.assistant.common.SteelSystemRegionAreaInfoService;
import com.steel.yfmall.cloud.assistant.common.impl.AuxiliaryDataRefresher;
import com.steel.yfmall.cloud.assistant.dto.para.common.ParaSteelSystemRegionAreaInfo;
import com.steel.yfmall.cloud.assistant.dto.para.goods.ParaProductLibCategoryBean;
import com.steel.yfmall.cloud.assistant.dto.para.goods.ParaProductSaleCompanyInfoBean;
import com.steel.yfmall.cloud.assistant.dto.para.oms.ParaMasterOrderInfo;
import com.steel.yfmall.cloud.assistant.dto.para.user.ParaBusinessStaffInfo;
import com.steel.yfmall.cloud.assistant.dto.para.view.ParaReceivingGoodsBean;
import com.steel.yfmall.cloud.assistant.goods.ProductLibCategoryService;
import com.steel.yfmall.cloud.assistant.goods.ProductSaleCompanyInfoBeanService;
import com.steel.yfmall.cloud.assistant.oms.MasterOrderInfoService;
import com.steel.yfmall.cloud.assistant.oms.MasterOrderOmsAPIService;
import com.steel.yfmall.cloud.assistant.po.common.SteelSystemRegionAreaInfoBean;
import com.steel.yfmall.cloud.assistant.po.goods.ProductLibCategory;
import com.steel.yfmall.cloud.assistant.po.goods.ProductSaleCompanyInfoBean;
import com.steel.yfmall.cloud.assistant.po.oms.MasterOrderInfo;
import com.steel.yfmall.cloud.assistant.po.oms.MasterOrderInoExtend;
import com.steel.yfmall.cloud.assistant.po.user.BusinessStaffInfo;
import com.steel.yfmall.cloud.assistant.po.user.StaffSaleArea;
import com.steel.yfmall.cloud.assistant.po.user.StaffSaleGroupInfo;
import com.steel.yfmall.cloud.assistant.po.view.ReceivingGoodsBean;
import com.steel.yfmall.cloud.assistant.user.BusinessStaffInfoService;
import com.steel.yfmall.cloud.assistant.utils.constants.ZgConstants;
import com.steel.yfmall.cloud.assistant.view.ReceivingGoodsBeanService;
import com.steel.yfmall.cloud.common.bean.result.APIResultDepotInfoBean;
import com.steel.yfmall.cloud.common.bean.result.APIResultSystemSalesAreaBean;
import com.steel.yfmall.cloud.components.utils.base.APIMsgBean;
import com.steel.yfmall.cloud.components.utils.base.ResponseCode;
import com.steel.yfmall.cloud.components.utils.utils.MobileBaseBeanUtils;
import com.steel.yfmall.cloud.components.utils.utils.PriceUtils;
import com.steel.yfmall.cloud.components.utils.utils.RandomUtil;
import com.steel.yfmall.cloud.components.utils.utils.UtilDate;
import com.steel.yfmall.cloud.oms.api.bean.enums.EnumShippingCode;
import com.steel.yfmall.cloud.oms.api.bean.request.*;
import com.steel.yfmall.cloud.oms.api.bean.response.ResponseCreateMasterOrder;
import com.steel.yfmall.cloud.oms.api.service.MasterOrderOutAPIService;
import com.steel.yfmall.cloud.product.api.SteelProductSubsidiaryService;
import com.steel.yfmall.cloud.product.bean.param.APIParaSteelProductLibProductFromBean;
import com.steel.yfmall.cloud.product.bean.response.APIResultSteelProductLibProductFromBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author yuchaohua
 * @version V1.0
 * @Title: MasterOrderAPIServiceImpl
 * @Package com.steel.yfmall.cloud.assistant.oms.impl
 * @Description: (用一句话描述该文件做什么)
 * @date 2021/1/20 15:24
 */
@Service
@Slf4j
public class MasterOrderOmsAPIServiceImpl implements MasterOrderOmsAPIService {


    /**
     * 接收订单配车信息订单确认
     * @Title: updateDriverOrderConfirm
     * @Description: (这里用一句话描述这个方法的作用)
     * @Param apiParaBean 参数说明
     * @return com.steel.yfmall.cloud.components.utils.base.APIMsgBean<java.lang.Boolean>    返回类型
     * @author yuchaohua
     * @date 2021/4/21 18:17
     */
    @Override
    public APIMsgBean<Boolean> updateDriverOrderConfirm(RequestPayBackBean apiParaBean) {
        APIMsgBean<Boolean> returnApiMsgBean = new APIMsgBean<>();
        try {
            returnApiMsgBean = masterOrderOutAPIService.updateDriverOrderConfirm(apiParaBean);
        } catch (Exception e) {
            log.error("function updateDriverOrderConfirm :", e);
        }
        return returnApiMsgBean;
    }

    /**
     * 创建订单变更单
     *
     * @param requestCreateMasterOrder
     * @return
     */
    protected APIMsgBean<ResponseCreateMasterOrder> createChangeOrder(RequestCreateMasterOrder requestCreateMasterOrder) {
        APIMsgBean<ResponseCreateMasterOrder> returnApiMsgBean = new APIMsgBean<>();
        try {
            returnApiMsgBean = masterOrderOutAPIService.createChangeOrder(requestCreateMasterOrder);
        } catch (Exception e) {
            log.error("function createChangeOrder :", e);
        }
        return returnApiMsgBean;
    }

    /**
     * 创建变更单信息
     *
     * @return com.steel.yfmall.cloud.components.utils.base.APIMsgBean<com.steel.yfmall.cloud.oms.api.bean.response.ResponseCreateMasterOrder>    返回类型
     * @Title: createChangeOrderFoZg
     * @Description: (这里用一句话描述这个方法的作用)
     * @Param apiParaBean 参数说明
     * @author yuchaohua
     * @date 2021/1/21 23:40
     */
    @Override
    public APIMsgBean<ResponseCreateMasterOrder> createChangeOrderFoZg(APIZgChangerOrderBean apiParaBean) {
        APIMsgBean<ResponseCreateMasterOrder> returnApiMsgBean = new APIMsgBean<>();
        try {
            ParaMasterOrderInfo paraBean = new ParaMasterOrderInfo();
            paraBean.setOutContractSn(apiParaBean.getOrderNo());
            paraBean.setOrderByValue("master_order_sn desc");
            MasterOrderInfo masterOrderInfo = masterOrderInfoService.selectMasterOrderInfoByPara(paraBean);
            if (masterOrderInfo == null) {
                returnApiMsgBean.setSoaStateBean(ResponseCode.buildEnumErrorSOAStateBean("订单不存在，订单变更失败"));
                return returnApiMsgBean;
            }
            // 查询订单和订单扩展信息
            MasterOrderInoExtend masterOrderInoExtend = masterOrderInfoService.selectBeanInoByPk(masterOrderInfo.getMasterOrderSn());
            // 创建订单bean
            RequestCreateMasterOrder requestCreateMasterOrder = new RequestCreateMasterOrder();
            List<RequestCreateMasterGoods> apiOrderGoodsList = new ArrayList<>(); // 商品信息
            List<RequestCreateMasterShip> apiOrderShipList = new ArrayList<>(); // 配送信息
            // 填充商品信息
            String orderGoodsInfo = fillOrderGoods(masterOrderInoExtend, apiOrderGoodsList, requestCreateMasterOrder, apiParaBean);
            if (StringUtils.isNotBlank(orderGoodsInfo)) {
                returnApiMsgBean.getSoaStateBean().setMessage(orderGoodsInfo);
                return returnApiMsgBean;
            }
            // 封装订单主信息
            processOrderInfoData(masterOrderInoExtend, requestCreateMasterOrder, apiParaBean);
            // 封装公司信息
            fillOrderCompanyData(masterOrderInoExtend, requestCreateMasterOrder, apiParaBean.getMain());
            // 填充订单详情和快递 信息
            String fillOrderInfoAndShipStr = fillOrderInfoAndShipBean(requestCreateMasterOrder, apiOrderShipList, apiOrderGoodsList, apiParaBean);
            if (StringUtils.isNotBlank(fillOrderInfoAndShipStr)) {
                returnApiMsgBean.setSoaStateBean(ResponseCode.buildEnumErrorSOAStateBean(fillOrderInfoAndShipStr));
                return returnApiMsgBean;
            }
            log.info("###############################");
            log.info("###############################");
            log.info(JSON.toJSONString(requestCreateMasterOrder));
            log.info("###############################");
            log.info("###############################");
            // 创建变更单
            returnApiMsgBean = createChangeOrder(requestCreateMasterOrder);
            // 如果变更单创建成功，建老的订单改为作废状态
            if (returnApiMsgBean != null && returnApiMsgBean.getData() != null){

                log.debug("订单变更： " + JSON.toJSONString(returnApiMsgBean));
                ParaMasterOrderInfo paraBeanOrderInfo = new ParaMasterOrderInfo();
                paraBeanOrderInfo.setMasterOrderSn(masterOrderInoExtend.getMasterOrderSn());

                MasterOrderInfo recordBean = new MasterOrderInfo();
                recordBean.setOrderStatus(2);
                recordBean.setContractStatus(2);
                recordBean.setCancelCode("8023");
                recordBean.setCancelReason("中冠订单变更取消订单");
                masterOrderInfoService.updateMasterOrderInfoByPara(recordBean,paraBeanOrderInfo);

                paraBeanOrderInfo = new ParaMasterOrderInfo();
                paraBeanOrderInfo.setMasterOrderSn(returnApiMsgBean.getData().getMasterOrderSn());
                recordBean = new MasterOrderInfo();
                recordBean.setRelatingOriginalSn(masterOrderInoExtend.getMasterOrderSn());
                recordBean.setShipStatus(masterOrderInoExtend.getShipStatus());
                masterOrderInfoService.updateMasterOrderInfoByPara(recordBean,paraBeanOrderInfo);
            }
        } catch (Exception e) {
            log.error("function createChangeOrder :", e);
        }
        return returnApiMsgBean;
    }

    /**
     * 地址信息和商品明细
     * @param requestCreateMasterOrder
     * @param apiOrderShipList
     * @param apiOrderGoodsList
     * @param apiParaBean
     * @return
     */
    private String fillOrderInfoAndShipBean(RequestCreateMasterOrder requestCreateMasterOrder, List<RequestCreateMasterShip> apiOrderShipList, List<RequestCreateMasterGoods> apiOrderGoodsList, APIZgChangerOrderBean apiParaBean) {
        String resStr = "";
        if (requestCreateMasterOrder == null || CollectionUtils.isEmpty(apiOrderGoodsList) || apiParaBean == null || apiParaBean.getMain() == null || CollectionUtils.isEmpty(apiParaBean.getDetails())) {
            return "订单中缺少商品明细～";
        }
        APIZgChangerOrderMainBean main = apiParaBean.getMain();

        RequestCreateMasterShip shipping = new RequestCreateMasterShip();
        ParaReceivingGoodsBean paraBean = new ParaReceivingGoodsBean();
        paraBean.setCustNo(main.getCustNo());
        paraBean.setRecOrderNo(main.getRecOrderNo());
        // 客户收货地址信息
        ReceivingGoodsBean receivingGoodsBean = receivingGoodsBeanService.getReceivingGoodsBeanByPara(paraBean);
        if (receivingGoodsBean == null) {
            return "收货地址不存在～";
        }
        shipping.setCountry("1");
        shipping.setConsignee(receivingGoodsBean.getRecName());
        shipping.setMobile(receivingGoodsBean.getPhone());
        shipping.setDistrict(receivingGoodsBean.getConty());
        shipping.setCity(receivingGoodsBean.getCity());
        shipping.setProvince(receivingGoodsBean.getProvince());
        //中冠系统编码
        shipping.setAreaCode(receivingGoodsBean.getAreaNo());
        shipping.setProvinceCode(receivingGoodsBean.getProvince());
        shipping.setCityCode(receivingGoodsBean.getCity());
        shipping.setDistrictCode(receivingGoodsBean.getConty());
        shipping.setLocaleCode(receivingGoodsBean.getSiteNo());
        shipping.setFinishAreaCode(receivingGoodsBean.getAreaNo());
        shipping.setZipcode(receivingGoodsBean.getZipCode());
        shipping.setAddress(receivingGoodsBean.getRecAddr());

        String shippingAddress = "";
        List<String> regionIdList = new ArrayList<>();
        regionIdList.add(receivingGoodsBean.getProvince());
        regionIdList.add(receivingGoodsBean.getCity());
        regionIdList.add(receivingGoodsBean.getConty());
        ParaSteelSystemRegionAreaInfo paraSteelSystemRegionAreaInfo = new ParaSteelSystemRegionAreaInfo();
        paraSteelSystemRegionAreaInfo.setRegionIdList(regionIdList);
        Map<String, SteelSystemRegionAreaInfoBean> regionAreaInfoBeanMap = steelSystemRegionAreaInfoService.getSteelSystemRegionAreaInfoMap(paraSteelSystemRegionAreaInfo);
        if (regionAreaInfoBeanMap != null && regionAreaInfoBeanMap.size() > 0 ){
            if (regionAreaInfoBeanMap.containsKey(receivingGoodsBean.getProvince())){
                shippingAddress += regionAreaInfoBeanMap.get(receivingGoodsBean.getProvince()).getRegionName();
            }
            if (regionAreaInfoBeanMap.containsKey(receivingGoodsBean.getCity())){
                shippingAddress += regionAreaInfoBeanMap.get(receivingGoodsBean.getCity()).getRegionName();
            }
            if (regionAreaInfoBeanMap.containsKey(receivingGoodsBean.getConty())){
                shippingAddress += regionAreaInfoBeanMap.get(receivingGoodsBean.getConty()).getRegionName();
            }
        }
        shipping.setShippingAddress(shippingAddress + receivingGoodsBean.getRecAddr());

        shipping.setZgRecOrderNo(main.getRecOrderNo());
        shipping.setFinishAreaCode(main.getAreaNo());
        shipping.setLocaleCode(main.getEndLocNo());
        shipping.setStartAreaCode(main.getBeginLocNo());
        //终点类型 F:工地  M市场
        shipping.setOrderAddressType(main.getSiteKind());
        // 运输方式 T汽运  R火运
        shipping.setShippingCartCode(main.getTransWayNo());
        //装载方式 1大载、2标载
        shipping.setLoadingMode(NumberUtils.toInt(main.getLoadWgtKind()));
        //车型要求 默认0 无要求， 1高厢，  2 低厢
        shipping.setShipCartType(NumberUtils.toInt(main.getCarKind()));
        //结算运费方式  D：一票送货  E：两票送货
        requestCreateMasterOrder.setShippingSettlModel(main.getTransWay());
        if (requestCreateMasterOrder.getIsPickUp() == 1) {
            shipping.setShippingCode(EnumShippingCode.PICKEDUP.getShippingCode());
        } else {
            shipping.setShippingCode(EnumShippingCode.LOGISTICS.getShippingCode());
        }
        // 填充商品信息
        shipping.setGoodsList(apiOrderGoodsList);
        // 填充券卡信息
        shipping.setCardInfos(null);
        // 身份证信息
        apiOrderShipList.add(shipping);
        requestCreateMasterOrder.setShipList(apiOrderShipList);
        return resStr;
    }

    /**
     * 填充商品信息
     *
     * @param apiOrderGoodsList
     * @param apiParaBean
     * @return
     */
    private String fillOrderGoods(MasterOrderInoExtend masterOrderInoExtend, List<RequestCreateMasterGoods> apiOrderGoodsList, RequestCreateMasterOrder requestCreateMasterOrder, APIZgChangerOrderBean apiParaBean) {
        String resStr = "";
        if (masterOrderInoExtend == null || apiParaBean == null || apiParaBean.getMain() == null || CollectionUtils.isEmpty(apiParaBean.getDetails())) {
            return "订单中缺少商品明细～";
        }
        APIZgChangerOrderMainBean main = apiParaBean.getMain();
        APIParaSteelProductLibProductFromBean apiParaSteelProductLibProductFromBean = new APIParaSteelProductLibProductFromBean();
        apiParaSteelProductLibProductFromBean.setProductFormCode(apiParaBean.getDetails().get(0).getProdType());
        ProductLibCategory productLibCategory = getProductLibCategory(apiParaSteelProductLibProductFromBean);
        // 订单日期
        Date orderDate = UtilDate.getDateFromBaseStr(main.getOrderDate());

        int totalGoodsQty = 0;
        int maxDeliveryCycle = 0;
        /**
         * 循环购物车商品信息
         */
        for (APIZgChangerOrderDetailsBean detailsBean : apiParaBean.getDetails()) {
            RequestCreateMasterGoods itemMasterGoods = new RequestCreateMasterGoods();
            itemMasterGoods.setExtensionCode("common");
            // 随机商品编码
            String goodsSn = "ZG" + RandomUtil.getRandomNumberString(4);
            MobileBaseBeanUtils.copyAllFields(detailsBean, itemMasterGoods);
            itemMasterGoods.setGoodsSn(goodsSn);// 商品编码
            itemMasterGoods.setCustomCode(goodsSn + "00000"); // 商品11位码
            requestCreateMasterOrder.setProductTypeNo(detailsBean.getProdType());

            //商品厚度
            if (StringUtils.isNotBlank(detailsBean.getOrderThick())) {
                itemMasterGoods.setProductThick(NumberUtils.toDouble(detailsBean.getOrderThick()));
            }
            //商品宽度
            if (StringUtils.isNotBlank(detailsBean.getOrderWidth())) {
                itemMasterGoods.setProductWidth(NumberUtils.toDouble(detailsBean.getOrderInnerDia()));
            }
            //商品长度
            if (StringUtils.isNotBlank(detailsBean.getOrderLength())) {
                itemMasterGoods.setProductLen(NumberUtils.toDouble(detailsBean.getOrderLength()));
            }
            // 长度上限
            if (StringUtils.isNotBlank(detailsBean.getOrderLengthMax())) {
                itemMasterGoods.setOrderLengthMax(NumberUtils.toDouble(detailsBean.getOrderLengthMax()));
            }
            // 长度下限
            if (StringUtils.isNotBlank(detailsBean.getOrderLengthMin())) {
                itemMasterGoods.setOrderLengthMin(NumberUtils.toDouble(detailsBean.getOrderLengthMin()));
            }
            // 钢卷外径
            if (StringUtils.isNotBlank(detailsBean.getOrderOuterDia())) {
                itemMasterGoods.setCoilOuterDia(NumberUtils.toDouble(detailsBean.getOrderOuterDia()));
            }
            // 钢卷内径
            if (StringUtils.isNotBlank(detailsBean.getOrderInnerDia())) {
                itemMasterGoods.setCoilInnerDia(NumberUtils.toDouble(detailsBean.getOrderInnerDia()));
            }
            itemMasterGoods.setProductTradeno(detailsBean.getTradeNo());
            itemMasterGoods.setProductApnno(detailsBean.getApnNo());
            itemMasterGoods.setProductGrade(detailsBean.getQuality());
            itemMasterGoods.setProductSizeMsg(detailsBean.getSizeMsg());
            itemMasterGoods.setCountWgtMode(detailsBean.getCountWgtMode());
            itemMasterGoods.setPerformanceFlag(detailsBean.getPerformanceFlag());
            itemMasterGoods.setToleranceType(detailsBean.getToleranceType());
            itemMasterGoods.setUltrasonicTestLevel(detailsBean.getUltrasonicTestLevel());
            itemMasterGoods.setStandName(detailsBean.getStandName());
            itemMasterGoods.setProductTypeNo(detailsBean.getProdType());

            itemMasterGoods.setShareBonus(0.00d);
            itemMasterGoods.setSellUnitModel(1);
            itemMasterGoods.setSalesMode(1);// 商品销售模式  1:自营，2:买断，3:寄售，4:直发
            itemMasterGoods.setPsrNo(detailsBean.getPsrNo());
            itemMasterGoods.setMscNo(detailsBean.getMscNo());
            itemMasterGoods.setDiagonalTolCode(detailsBean.getDiagonalTolCode());
            itemMasterGoods.setCutedgeCode(detailsBean.getCutEdgeCode());
            itemMasterGoods.setColorName("无色");// 颜色名称
            itemMasterGoods.setSizeName("标准");// 尺寸名称
            itemMasterGoods.setIntegral(0.00D);
            itemMasterGoods.setIntegralMoney(0.00D);
            // 发发周期
            if (StringUtils.isNotBlank(detailsBean.getShipReqDate())) {
                itemMasterGoods.setDeliveryCycle(UtilDate.differentDays(orderDate, UtilDate.getDateFromBaseStr(detailsBean.getShipReqDate())));
            }
            // 实际发货重量(吨)
            itemMasterGoods.setSendWeight(NumberUtils.toDouble(detailsBean.getOrderWgt()));
            // 订购数量
            if (StringUtils.isNotBlank(detailsBean.getOrderQty())) {
                itemMasterGoods.setGoodsQty(NumberUtils.toInt(detailsBean.getOrderQty()));
                totalGoodsQty += NumberUtils.toInt(detailsBean.getOrderQty());
            }
            itemMasterGoods.setUnitTitle(masterOrderInoExtend.getUnitTitle());
            itemMasterGoods.setSellerCode(masterOrderInoExtend.getSiteCode());
            itemMasterGoods.setDepotCode(detailsBean.getWarehouseNo());
            // 仓库信息
            APIResultDepotInfoBean depotInfoBean = getDepotInfoBean(detailsBean.getWarehouseNo());
            if (depotInfoBean != null) {
                itemMasterGoods.setDepotName(depotInfoBean.getDepotName());
            }
            itemMasterGoods.setExpectedShipDate(UtilDate.getDateFromBaseStr(detailsBean.getShipReqDate()));
            //扩展服务收费
            itemMasterGoods.setGoodsExtraPrice(0.00D);
            itemMasterGoods.setProductWgt(NumberUtils.toDouble(detailsBean.getPieceWgt()));// 单件重量
            // 单件价格
            double priceOne = PriceUtils.mul(NumberUtils.toDouble(detailsBean.getPieceWgt()), NumberUtils.toDouble(detailsBean.getOrderPrice()));

            // 成交价格
            itemMasterGoods.setTransactionPrice(priceOne);
            itemMasterGoods.setGoodsPrice(priceOne);
            itemMasterGoods.setCostPrice(priceOne);
            StringBuffer goodsName = new StringBuffer();
            if (productLibCategory != null) {
                goodsName.append(" ").append(productLibCategory.getCateName());
                itemMasterGoods.setGoodsThumb(productLibCategory.getDefaultProductUrl()); // 图片url
            }
            if (StringUtils.isNotBlank(itemMasterGoods.getProductTradeno())) {
                goodsName.append(" ").append(itemMasterGoods.getProductTradeno());
            }
            goodsName.append(" ").append(itemMasterGoods.getProductThick());
            goodsName.append("*").append(itemMasterGoods.getProductWidth());
            goodsName.append("*").append(itemMasterGoods.getProductLen());
            if (StringUtils.isNotBlank(itemMasterGoods.getDepotName())) {
                goodsName.append(" ").append(itemMasterGoods.getDepotName());
            }
            goodsName.append(" ").append(itemMasterGoods.getGoodsSn());
            itemMasterGoods.setGoodsName(goodsName.toString()); // 商品名称

            itemMasterGoods.setMarketPrice(NumberUtils.toDouble(detailsBean.getOrderPrice()));// 单价
            // 成交单价/吨
            itemMasterGoods.setTransactionUnitPrice(NumberUtils.toDouble(detailsBean.getOrderPrice()));// 单价
            // 起点代码
            itemMasterGoods.setStartAreaCode(detailsBean.getBeginLocNo());
            // 运费单价
            itemMasterGoods.setShippingFee(NumberUtils.toDouble(detailsBean.getFreightPrice()));
            if (itemMasterGoods.getDeliveryCycle() > maxDeliveryCycle) {
                maxDeliveryCycle = itemMasterGoods.getDeliveryCycle();
            }
            apiOrderGoodsList.add(itemMasterGoods);
        }
        requestCreateMasterOrder.setGoodsQty(totalGoodsQty);
        requestCreateMasterOrder.setTotalDeliveryCycle(maxDeliveryCycle);
        return resStr;
    }

    /**
     * 封装订单主信息
     *
     * @param masterOrderInoExtend
     * @param requestCreateMasterOrder
     * @param apiParaBean
     */
    protected void processOrderInfoData(MasterOrderInoExtend masterOrderInoExtend, RequestCreateMasterOrder requestCreateMasterOrder, APIZgChangerOrderBean apiParaBean) {
        requestCreateMasterOrder.setUserName(masterOrderInoExtend.getUserName());
        requestCreateMasterOrder.setUserMobile(masterOrderInoExtend.getUserMobile());
        requestCreateMasterOrder.setShopName(masterOrderInoExtend.getShopName());
        requestCreateMasterOrder.setChannelCode(masterOrderInoExtend.getChannelCode());
        requestCreateMasterOrder.setSiteCode(masterOrderInoExtend.getSiteCode());
        requestCreateMasterOrder.setReferer(masterOrderInoExtend.getReferer());
        requestCreateMasterOrder.setToBuyer(apiParaBean.getReason());
        requestCreateMasterOrder.setUnitTitle(masterOrderInoExtend.getUnitTitle());
        requestCreateMasterOrder.setSourceCode(masterOrderInoExtend.getChannelCode());
        requestCreateMasterOrder.setOutContractSn(apiParaBean.getOrderNo());
        requestCreateMasterOrder.setPayCode("balance");
        requestCreateMasterOrder.setPayStatus(2);

        APIZgChangerOrderMainBean main = apiParaBean.getMain();
        // 产销合同状态
        requestCreateMasterOrder.setOutOrderStatus(main.getStatus());
        requestCreateMasterOrder.setShippingSettlModel(main.getTransWay());

        /** 运费担当
         * A:客提
         * D:一票送货-锁定运费
         * H:一票送货-实际运费
         * E:两票送货
         * F:自提
         */
        if (StringUtils.equalsIgnoreCase(main.getTransWay(), ZgConstants.TRANS_WAY_A) || StringUtils.equalsIgnoreCase(main.getTransWay(), ZgConstants.TRANS_WAY_F)) {
            requestCreateMasterOrder.setIsPickUp(1);
        }

        // 配送总费用
        if (StringUtils.isNotBlank(main.getFreightAmt())) {
            requestCreateMasterOrder.setShippingTotalFee(NumberUtils.toDouble(main.getFreightAmt()));
        }
        // 订购总金额
        if (StringUtils.isNotBlank(main.getOrderAmt())) {
            requestCreateMasterOrder.setTotalFee(NumberUtils.toDouble(main.getOrderAmt()));
            requestCreateMasterOrder.setMoneyPaid(NumberUtils.toDouble(main.getOrderAmt()));
        }
        // 货款金额
        if (StringUtils.isNotBlank(main.getProdAmt())) {
            requestCreateMasterOrder.setGoodsAmount(NumberUtils.toDouble(main.getProdAmt()));
        }

        // 订购总重量
        requestCreateMasterOrder.setGoodsWeight(NumberUtils.toDouble(main.getOrderWgt()));
        requestCreateMasterOrder.setVersion(NumberUtils.toInt(main.getOrderVer()));

        requestCreateMasterOrder.setOutProductClassifyCode(main.getProdClass());
//        requestCreateMasterOrder.setProductTypeNo(main.getProdType());
        //订单类型    0  I:现货订单   7  P:生产订单
        if (StringUtils.isNotBlank(main.getContractTypeB()) && ZgConstants.orderContractTypeBMap.containsKey(main.getContractTypeB())) {
            requestCreateMasterOrder.setOrderType(ZgConstants.orderContractTypeBMap.get(main.getContractTypeB()));
        }

    }

    /**
     * 封装公司信息
     *
     * @param masterOrderInoExtend
     * @param requestCreateMasterOrder
     * @param zgMainBean
     */
    protected void fillOrderCompanyData(MasterOrderInoExtend masterOrderInoExtend, RequestCreateMasterOrder requestCreateMasterOrder, APIZgChangerOrderMainBean zgMainBean) {
        if (requestCreateMasterOrder == null || zgMainBean == null || masterOrderInoExtend == null) {
            return;
        }
        RequestCreateMasterCompany requestCreateMasterCompany = new RequestCreateMasterCompany();
        // 定价区域
        requestCreateMasterCompany.setPriceAreaCode(zgMainBean.getDeliveryArea());
        APIResultSystemSalesAreaBean priceSaleArea = getAPIParaSystemSalesArea(zgMainBean.getDeliveryArea());
        if (null != priceSaleArea) {
            requestCreateMasterCompany.setPriceAreaName(priceSaleArea.getSalesName());
        } else {
            requestCreateMasterCompany.setPriceAreaName(zgMainBean.getDeliveryArea());
        }
        //销售分公司信息
        requestCreateMasterCompany.setSalesBranchCode(zgMainBean.getSignedComp());
        ProductSaleCompanyInfoBean saleCompanyInfoBean = getProductSaleCompanyInfoBean(zgMainBean.getSignedComp());
        if (null != saleCompanyInfoBean) {
            requestCreateMasterCompany.setSalesBranchName(saleCompanyInfoBean.getSaleCompanyName());
        } else {
            requestCreateMasterCompany.setSalesBranchName(zgMainBean.getSignedComp());
        }
        // 销售员
        requestCreateMasterCompany.setStaffCode(zgMainBean.getSalesMan());
        BusinessStaffInfo businessStaffInfo = getBusinessStaffInfo(requestCreateMasterCompany.getStaffCode());
        if (businessStaffInfo != null) {
            requestCreateMasterCompany.setStaffName(businessStaffInfo.getStaffName());
        } else {
            requestCreateMasterCompany.setStaffName(requestCreateMasterCompany.getStaffCode());
        }
        // 销售区域
        requestCreateMasterCompany.setSaleAreaCode(zgMainBean.getSalesArea());
        StaffSaleArea staffSaleArea = getSaleAreaBean(zgMainBean.getSalesArea());
        if (staffSaleArea != null) {
            requestCreateMasterCompany.setSaleAreaName(staffSaleArea.getSaleAreaName());
        }
        // 业务组信息
        requestCreateMasterCompany.setSaleGroupCode(zgMainBean.getSalesGroup());
        StaffSaleGroupInfo saleGroupInfoBean = getSaleGroupInfoBean(zgMainBean.getSalesGroup());
        if (saleGroupInfoBean != null) {
            requestCreateMasterCompany.setSaleGroupName(saleGroupInfoBean.getSaleGroupName());
        }
        requestCreateMasterCompany.setCompanyCode(masterOrderInoExtend.getCompanyCode());
        requestCreateMasterCompany.setCompanyName(masterOrderInoExtend.getCompanyName());

        //公司类型 1内部公司、2外部公司
        requestCreateMasterCompany.setCompanyType(masterOrderInoExtend.getCompanyType());
        requestCreateMasterCompany.setInsteadUserName(masterOrderInoExtend.getInsteadUserName());
        requestCreateMasterCompany.setProtocolType(masterOrderInoExtend.getProtocolType());
        requestCreateMasterOrder.setOutCustomerContractSn(zgMainBean.getContractNo());
        requestCreateMasterOrder.setRequestCreateMasterCompany(requestCreateMasterCompany);

    }

    /**
     * 获取仓库信息
     *
     * @param depotCode
     * @return StoreInfoBean
     */
    public APIResultDepotInfoBean getDepotInfoBean(String depotCode) {
        if (StringUtils.isNotBlank(depotCode)) {
            try {
                APIResultDepotInfoBean result = auxiliaryDataRefresher.getDepotInfoBean(depotCode);
                return result;
            } catch (Exception ex) {
                log.error("function getDepotInfoBean", ex);
            }
        }
        return null;
    }

    /**
     * 获取销售地区
     *
     * @param saleAreaCode
     * @return
     */
    public StaffSaleArea getSaleAreaBean(String saleAreaCode) {
        if (StringUtils.isNotBlank(saleAreaCode)) {
            try {
                StaffSaleArea result = auxiliaryDataRefresher.getSaleAreaBean(saleAreaCode);
                return result;
            } catch (Exception ex) {
                log.error("function getSaleAreaBean", ex);
            }
        }
        return null;
    }

    /**
     * 获取销售组信息
     *
     * @param saleGroupCode
     * @return
     */
    public StaffSaleGroupInfo getSaleGroupInfoBean(String saleGroupCode) {
        if (StringUtils.isNotBlank(saleGroupCode)) {
            try {
                StaffSaleGroupInfo result = auxiliaryDataRefresher.getSaleGroupInfoBean(saleGroupCode);
                return result;
            } catch (Exception ex) {
                log.error("function getSaleGroupInfoBean", ex);
            }
        }
        return null;
    }


    /**
     * 获取定价区域信息
     *
     * @param saleAreaCode
     * @return StoreInfoBean
     */
    public APIResultSystemSalesAreaBean getAPIParaSystemSalesArea(String saleAreaCode) {
        if (StringUtils.isNotBlank(saleAreaCode)) {
            try {
                APIResultSystemSalesAreaBean result = auxiliaryDataRefresher.getAPIParaSystemSalesAreaBean(saleAreaCode);
                return result;
            } catch (Exception ex) {
                log.error("function getAPIParaSystemSalesArea", ex);
            }
        }
        return null;
    }

    /**
     * 获取销售公司信息
     *
     * @param saleCompanyCode
     * @return
     */
    public ProductSaleCompanyInfoBean getProductSaleCompanyInfoBean(String saleCompanyCode) {
        if (StringUtils.isNotBlank(saleCompanyCode)) {
            try {
                ParaProductSaleCompanyInfoBean paraBean = new ParaProductSaleCompanyInfoBean();
                paraBean.setSaleCompanyCode(saleCompanyCode);
                ProductSaleCompanyInfoBean result = productSaleCompanyInfoBeanService.getProductSaleCompanyInfoBeanByPara(paraBean);
                return result;
            } catch (Exception ex) {
                log.error("function getProductSaleCompanyInfoBean", ex);
            }
        }
        return null;
    }

    /**
     * 企业业务员工信息
     *
     * @param staffCode
     * @return
     */
    public BusinessStaffInfo getBusinessStaffInfo(String staffCode) {
        if (StringUtils.isNotBlank(staffCode)) {
            try {
                ParaBusinessStaffInfo paraBusinessStaffInfo = new ParaBusinessStaffInfo();
                paraBusinessStaffInfo.setStaffCode(staffCode);
                BusinessStaffInfo result = businessStaffInfoService.getBusinessStaffInfoByPara(paraBusinessStaffInfo);
                return result;
            } catch (Exception ex) {
                log.error("function getBusinessStaffInfo", ex);
            }
        }
        return null;
    }

    /**
     * 获取商品分类信息
     *
     * @param apiParaBean
     * @return
     */
    public ProductLibCategory getProductLibCategory(APIParaSteelProductLibProductFromBean apiParaBean) {
        ProductLibCategory returnBean = null;
        try {
            APIMsgBean<APIResultSteelProductLibProductFromBean> apiMsgBean = steelProductSubsidiaryService.getSteelProductLibProductFromByCode(apiParaBean);
            if (apiMsgBean != null && apiMsgBean.getData() != null) {
                ParaProductLibCategoryBean paraProductLibCategoryBean = new ParaProductLibCategoryBean();
                paraProductLibCategoryBean.setCategoryId(apiMsgBean.getData().getCategoryId());
                returnBean = productLibCategoryService.getProductLibCategory(paraProductLibCategoryBean);
            }
        } catch (Exception e) {
            log.error("获取商品分类信息失败 ：" + JSON.toJSONString(apiParaBean));
        }
        return returnBean;
    }

    @Resource
    private SteelProductSubsidiaryService steelProductSubsidiaryService;

    @Resource
    private MasterOrderOutAPIService masterOrderOutAPIService;

    @Resource
    private MasterOrderInfoService masterOrderInfoService;

    /**
     * 缓存信息
     */
    @Resource
    private AuxiliaryDataRefresher auxiliaryDataRefresher;

    /**
     * 员工信息
     */
    @Resource
    private BusinessStaffInfoService businessStaffInfoService;

    /**
     * 销售公司
     */
    @Resource
    private ProductSaleCompanyInfoBeanService productSaleCompanyInfoBeanService;

    /**
     * 分类
     */
    @Resource
    private ProductLibCategoryService productLibCategoryService;

    /**
     * 收货人管理数据
     */
    @Resource
    private ReceivingGoodsBeanService receivingGoodsBeanService;

    /**
     * 地址信息
     */
    @Resource
    private SteelSystemRegionAreaInfoService steelSystemRegionAreaInfoService;

}
